package com.caird.pmp.iot.message;

import com.caird.common.utils.ClassUtils;
import com.caird.pmp.iot.message.impl.ServerMessage8001;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("BbMessageFactory")
public class MessageFactory {

    private static Map<String, Class<? extends IMessage>> messages = new HashMap<>();

    static {
        List<Class<? extends IMessage>> classList = ClassUtils.getAllClassByInterface(IMessage.class);

        for (Class<? extends IMessage> c : classList) {
            messages.put(c.getName().substring(c.getName().length()-4), c);
        }
    }

    public static IMessage make(String id) {

        Class<? extends IMessage> c = messages.get(id);

        IMessage message = null;

        if(null != c) {
            try {
                message = c.newInstance();
            } catch (InstantiationException | IllegalAccessException ignored) {
                log.warn("New Message 0x" + id + " Exception.");
            }

        }

        return message;
    }


    public static IMessage make(short id) {
        return make(String.format("%04X", id));
    }

    public static ServerMessage8001 make8001(MessageBase deviceMessage, byte result) {
        ServerMessage8001 serverMessage = new ServerMessage8001();
        serverMessage.setSimNo(deviceMessage.getSimNo());
        serverMessage.setFlowNo((short)0);
        return serverMessage;
    }
}
